<template>
  <div class="mb60 mt60">
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      fixed
      title="校园超市"
    />
    <van-search
      @search="search"
      shape="round"
      v-model="keywords"
      placeholder="请输入搜索关键词"
    />
    <div class="history-title">
      <h3>历史搜索</h3>
      <span @click="clearKeywords">清空历史记录</span>
    </div>
    <div class="history-list">
      <div
        @click="keywordsClick(item)"
        v-for="(item, index) in keywordsList"
        :key="index"
      >
        {{ item }}
      </div>
    </div>
    <!-- 商品列表 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list
        :immediate-check="false"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-card
          lazy-load
          @click="goGoods(item.id)"
          v-for="item in goodsList"
          :key="item.id"
          :price="item.price"
          :title="item.goodsname"
          :thumb="$baseUrl + item.img"
        />
      </van-list>
      <van-empty
        v-if="goodsList.length === 0"
        description="暂无搜索结果"
      ></van-empty>
    </van-pull-refresh>
  </div>
</template>

<script>
import { usePager } from "@/plugins/hooks";
import { ref, onMounted, watch, inject } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showToast } from "vant";
export default {
  setup() {
    const { page, size, totalCount: total } = usePager();
    const isLoading = ref(false);
    const loading = ref(false);
    const finished = ref(false);
    const keywords = ref("");
    const goodsList = ref([]);
    const keywordsList = ref([]);
    const route = useRoute();
    const router = useRouter();
    const axios = inject("axios");

    // 读取本地存储中的搜索关键词
    const getSearchHistory = () => {
      keywordsList.value = JSON.parse(
        localStorage.getItem("keywordsList") || "[]"
      );
    };
    onMounted(() => {
      if (route.query.keywords) {
        keywords.value = route.query.keywords;
      }
      // 读取搜索关键词
      getSearchHistory();
    });

    watch(keywords, () => {
      goodsList.value = [];
      page.value = 1;
      finished.value = false;
    });

    const search = () => {
      if (!keywords.value) {
        showToast("请输入搜索关键词");
      }
      router.replace({
        name: "search",
        query: { keywords: keywords.value, rand: Math.random() },
      });
      // 通过本地存储记录搜索关键词
      keywordsList.value = JSON.parse(
        localStorage.getItem("keywordsList") || "[]"
      );
      if (!keywordsList.value.includes(keywords.value)) {
        keywordsList.value.unshift(keywords.value);
      }
      // 更新本地存储
      localStorage.setItem("keywordsList", JSON.stringify(keywordsList.value));
      axios
        .get("/search", {
          params: {
            keywords: keywords.value,
            page: page.value,
            size: size.value,
          },
        })
        .then((res) => {
          if (res.code === 200) {
            goodsList.value = [...goodsList.value, ...res.list.goodsList];
            total.value = res.list.total;
            // 关闭loading
            loading.value = false;
            isLoading.value = false;
            if (total.value === goodsList.length) {
              // 数据加载完毕
              finished.value = true;
            }
          }
        });
    };

    const onRefresh = () => {
      // 下拉loading效果会自动开启, 开发者只需要在数据请求结束之后或者不需loading的时候关闭loading效果即可
      if (!keywords.value) {
        isLoading.value = false;
        showToast("请输入搜索关键词");
        return false;
      }
      page.value = 1;
      goodsList.value = [];
      search();
    };

    const onLoad = () => {
      // 上拉加载loading效果, 会自动开启, 开发者只需要是在数据请求完毕之后, 关闭loading效果即可
      if (goodsList.value.length < total.value) {
        page.value += 1;
        search();
      }
    };

    const goGoods = (id) => {
      router.push({ name: "goods", query: { id } });
    };

    const clearKeywords = () => {
      // 清除本地存储中的搜索关键词
      localStorage.removeItem("keywordsList");
      // 更新页面
      keywordsList.value = [];
    };

    const keywordsClick = (key) => {
      keywords.value = key;
      search();
    };

    return {
      page,
      size,
      total,
      isLoading,
      loading,
      finished,
      keywords,
      goodsList,
      keywordsList,
      onRefresh,
      onLoad,
      goGoods,
      clearKeywords,
      keywordsClick,
      search,
    };
  }
};
</script>

<style scoped>
.history-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}

.history-title > span {
  font-size: 14px;
  color: #666;
}

.history-list {
  padding: 10px;
  color: #999;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
</style>